import Cac from "node-cache";
// 先提供一个同步版本的获取信息
export class CacheMoudle<T> extends Cac {
    /**5s 检查一次 */
    static async init() {
        return true;
    }

    /**
     * 创建cache
     * @param name 模块名字 如果没有名字将不支持自动update功能
     * @param ttl 数据有效期 等于0的时候不更新 小于0的时候不计算ttl
     */
    static createCache<T>(name?: string, ttl?: number, keep?: Cac.Options): CacheMoudle<T> {
        keep = keep || {};
        // 默认不开启克隆模式
        keep.useClones = keep.useClones || false;
        ttl = ttl || 0;
        if (ttl < 0) ttl = 0;
        keep.stdTTL = Math.floor(ttl / 1000);
        if (name == undefined) {
            return new CacheMoudle<T>(keep);
        }
        else {
            if (!this.cacheMap.hasOwnProperty(name)) {
                this.cacheMap[name] = new CacheMoudle<T>(keep);
            }
            return this.cacheMap[name];
        }
    }

    // 移除cache
    static removeCache(name: string) {
        delete this.cacheMap[name]
    }

    static cacheMap: { [key: string]: CacheMoudle<any> } = {};

    hasOwnProperty(key: string) {
        return this.has(key);
    }

    /** 查询且续订 */
    get<T>(
        key: Cac.Key
    ) {
        if (this.has(key)) {
            super.ttl(key, this.options.stdTTL || Infinity)
        }
        return super.get<T>(key)
    }

    /** 不续订的查询 */ 
    getNttl<T>(
        key: Cac.Key
    ) {
        // if (this.has(key)) {
        //     super.ttl(key, this.options.stdTTL || Infinity)
        // }
        return super.get<T>(key)
    }

    /**
     * 遍历内容
     * @param cb 当方法返回 true时 结束遍历(break)
     */
    forEach(cb: (value: T, key: string) => boolean | void) {
        let kStrings = this.keys()
        for (let i = 0; i < kStrings.length; i++) {
            let key = kStrings[i];
            let value = this.get<T>(key);
            if (!value) continue;
            if (cb(value, key)) {
                return value
            }
        }
        return undefined;
    }

    clear() {
        return this.close()
    }
}